import axios from "axios";

const service = axios.create({
  baseURL: "http://localhost:5560",
  timeout: 60000,
});

// 接口打印处理函数
function log(
  bgColor: string,
  fontColor: string = "#fff",
  isSuccess: string | undefined,
  url: string = "",
  method: string | undefined,
  params: any,
  data: any
) {
  console.log("");
  console.log(
    `%c${"↓ ===================== ↓"}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"响应状态："}${isSuccess || "后台接口报错"}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"请求地址："}${url}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"请求类型："}${method || "post"}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"请求参数："}${params || "无参请求"}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"响应数据："}${data}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log(
    `%c${"↑ ===================== ↑"}`,
    `background:${bgColor}; font-size: 14px;color:${fontColor};`
  );
  console.log("");
}

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 判断是否为 h5 还是 pc
    const isMobile = !navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    // 在发送请求之前做些什么
    config.headers.Authorization = `Bearer ${
      window.localStorage.getItem("token") || ""
    }`;
    config.headers.platform = isMobile ? "pc" : "mobile";
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.status === 2000) {
      log(
        "green",
        "#fff",
        response.data.message || response.data.msg || "成功",
        response.request.responseURL,
        response.config.method,
        JSON.parse(response.config.data),
        response.data
      );
    } else {
      log(
        "red",
        "#000",
        response.data.message || response.data.msg || "成功",
        response.request.responseURL,
        response.config.method,
        JSON.parse(response.config.data),
        response.data
      );
    }
    // 对响应数据做点什么
    return response.data;
  },
  (error) => {
    // 对响应错误做点什么
    let errMsg =
      "请求报错 状态码：" +
      error.response.status +
      "; code: " +
      error.code +
      "; 报错 msg: " +
      error.message;
    log(
      "red",
      "#000",
      errMsg,
      error.request.responseURL,
      error.config.method,
      JSON.parse(error.config.data),
      error.response.data
    );
    let data = error.response.data;
    return Promise.reject(data);
  }
);

export default service;
